package com.tianshi.pxx.service.impl;


import com.tianshi.pxx.mapper.ProductMapper;
import com.tianshi.pxx.pojo.entity.Product;
import com.tianshi.pxx.service.ProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Set;

@Service
public class ProductServiceImpl implements ProductService {

    @Autowired
    private ProductMapper productMapper;
    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    @Cacheable(value = "product-all")
    public List<Product> getAll() {
        return productMapper.selectAll();
    }

    @Override
    @Cacheable(value = "product-search",key = "#keyword")
    public List<Product> search(String keyword) {
        return productMapper.search(keyword);
    }

    @Override
//    @CacheEvict(value = "product",key = "'all-products'")
    public int delete(int id) {
        //清空redis缓存
         redisTemplate.delete(deleteKeys("product*"));
         return productMapper.delete(id);
    }

    @Override
    @Cacheable(value = "product-searchByPrice",key = "#minPrice+'~'+#maxPrice")
    public List<Product> searchProductsByPrice(Double minPrice, Double maxPrice) {
        return productMapper.selectByPrice(minPrice, maxPrice);
    }

    @Override
//    @CacheEvict(value = "product",key = "'all-products'")
    public void updateProduct(Product product) {
        //清空redis缓存
        redisTemplate.delete(deleteKeys("product*"));
        productMapper.update(product);
    }

    @Override
//    @CacheEvict(value = "product",key = "'all-products'")
    public void addProduct(Product product) {
        //清空redis缓存
        redisTemplate.delete(deleteKeys("product*"));
        productMapper.insert(product);
    }

    private Set<String> deleteKeys(String pattern){
        Set<String> keys = redisTemplate.keys(pattern);
        for(String key:keys){
            System.out.println(key);
        }
        return keys;
    }
}
